package com.csdj.music.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csdj.music.config.SmsProperties;
import com.csdj.music.service.ConsumerService;
import com.csdj.music.utils.RandomUtil;
import com.csdj.music.vo.Consumer;
import com.csdj.music.vo.RespBean;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.aliyuncs.dysmsapi.model.v20170525.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: PhoneNumberSendCodeService
 * @Author: ZouLi
 * @Description: 手机号发送验证码业务层
 * @Date: 2023/3/15 15:22
 **/
@Service
public class PhoneNumberSendCodeService {

    /**
     * RedisTemplate
     **/
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * ConsumerService
     **/
    @Autowired
    private ConsumerService consumerService;

    /**
     * @Description: 发送验证码
     * @Param [phone]
     * @Return com.csdj.music.vo.RespBean
     * @Throws
     **/
    public RespBean sendRegistCode(String phone, String status){
        if (StringUtils.equals(status, "regist")){
            int count = consumerService.count(new QueryWrapper<Consumer>().eq("phone_num", phone));
            if (count > 0){
                return RespBean.error("手机号已被注册！");
            }
        }
        // 初始化ascClient需要的几个参数
        final String product = "Dysmsapi";// 短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";// 短信API产品域名（接口地址固定，无需修改）
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            e.printStackTrace();
        }

        DefaultProfile profile = DefaultProfile.getProfile(SmsProperties.REGION_Id, SmsProperties.KEY_ID, SmsProperties.KEY_SECRET);

        IAcsClient client = new DefaultAcsClient(profile);

        String code = RandomUtil.getSixBitRandom();

        // 创建请求对象
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(SmsProperties.SIGN_NAME);
        request.setTemplateCode(SmsProperties.TEMPLATE_CODE);
        request.setTemplateParam("{\"code\":\""+code+"\"}");
        try {
            // 获取响应对象
            SendSmsResponse response = client.getAcsResponse(request);
            ValueOperations<String, Object> redis = redisTemplate.opsForValue();
            // 缓存，可存在3分钟
            if (StringUtils.equals(status,"regist")){
                redis.set("registCode", code, 3, TimeUnit.MINUTES);
            }else if (StringUtils.equals(status,"login")){
                redis.set("loginCode", code, 3, TimeUnit.MINUTES);
            }
            return RespBean.success("发送成功！",new Gson().toJson(response));
        } catch (ServerException e) {
            return RespBean.error("未知错误！发送失败！", e.getMessage());
        } catch (ClientException e) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("ErrCode", e.getErrCode());
            map.put("ErrMsg", e.getErrMsg());
            map.put("RequestId", e.getRequestId());
            return RespBean.error("发送失败，错误信息：", map);
        }
    }
}
